package com.heyqing.topic.AddTwoNumbers_0002;

import java.util.Objects;

/**
 * ClassName:AddTwoNumbers
 * Package:com.heyqing
 * Description:
 *
 * @Date:2024/5/16
 * @Author:Heyqing
 */
public class AddTwoNumbers_0002 {
    /**
     * 迭代算法
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbersIterative(ListNode l1, ListNode l2) {
        // 使用哑节点简化操作
        ListNode dummyHead = new ListNode(0);
        ListNode res = dummyHead;
        int flag = 0;
        while (Objects.nonNull(l1) || Objects.nonNull(l2)){
            int x = (Objects.nonNull(l1)) ? l1.val : 0;
            int y = (Objects.nonNull(l2)) ? l2.val : 0;
            int valSum = x + y + flag;
            //  创建新的 ListNode 并设置其 val
            res.next = new ListNode(valSum % 10);
            flag = valSum / 10;
            if (Objects.nonNull(l1)){
                l1 = l1.next;
            }
            if (Objects.nonNull(l2)){
                l2 = l2.next;
            }
            res = res.next;
        }
        if (flag > 0){
            //  如果有进位，在最后添加一个节点
            res.next = new ListNode(flag);
        }
        return dummyHead.next;
    }

    /**
     * 递归算法
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbersRecursive(ListNode l1, ListNode l2) {
        ListNode dummyHeat = new ListNode(0);
        ListNode res = dummyHeat;
        int sum = 0;
        if (Objects.nonNull(l1)&&Objects.nonNull(l2)){
            sum = l1.val + l2.val;
            if (sum >= 10){
                if (Objects.nonNull(l1.next)){
                    l1.next.val += 1;
                }else {
                    l1.next = new ListNode(1);
                }
            }
            res.next = new ListNode(sum%10);
        }
        if (Objects.nonNull(l1.next) || Objects.nonNull(l2.next)){
            if (Objects.isNull(l1.next)){
                l1.next = new ListNode(0);
            }
            if (Objects.isNull(l2.next)){
                l2.next = new ListNode(0);
            }
            res.next.next = addTwoNumbersRecursive(l1.next,l2.next);
        }
        return dummyHeat.next;
    }
}
